package corp.edu.amadeus.core.bluetooth.wrapper;

import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import java.util.List;
import java.util.ArrayList;
import javax.bluetooth.DeviceClass;
import org.apache.log4j.Logger;

public class RemoteDeviceWrapper  {

	private static Logger log = Logger.getLogger(RemoteDeviceWrapper.class);

	private DeviceClass clazz;
	private RemoteDevice internal_device;
	private List<ServiceRecord> services =
		new ArrayList<ServiceRecord>();
	private String obex_url = "";

	public RemoteDeviceWrapper(DeviceClass c, RemoteDevice device) {
		this.internal_device = device;
		this.clazz = c;
	}

	public void addServices(ServiceRecord[] servRecord) {
		for(ServiceRecord s : servRecord) {
			this.services.add(s);
		}
		this.setOBEXServiceURL();
	}

	public RemoteDevice getInternalDevice() {
		return this.internal_device;
	}

	public List<ServiceRecord> getServices() {
		return this.services;
	}

	public String getBtAddress() {
		return this.internal_device.getBluetoothAddress();
	}

	public String getFriendlyName() {
		String friendlyName = "Not supported";
		try {
			friendlyName = this.internal_device.getFriendlyName(true);
		} catch(Exception e) {
			log.error("FriendlyName not supported in device " +
					this.getBtAddress());
		}
		return friendlyName;
	}

	public void showServices() {
		log.debug(" --- Enabled services.urls --------");
		for (ServiceRecord service : this.services) {
            String url = service.getConnectionURL(
            		ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
            log.debug("Service-URL: " + url);
        }
	}

	public boolean isOBEXDevice() {
		return "".equals(this.obex_url)?false:true;
	}

	private void setOBEXServiceURL() {
		String url = "", protocol = "";
		for(ServiceRecord service: this.services) {
			url = service.getConnectionURL(
					ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
			int index= url.indexOf(':');
			protocol= url.substring(0, index);
			if("btgoep".equals(protocol)) {
				this.obex_url = url;
				break;
			}
		}
	}

	public String getOBEXURL() {
		return this.obex_url;
	}

}